<?php
/**
 * 管理员模型
 * 贵州MIC网络信息技术
 * 楚羽幽 《name_cyu@foxmail.com》
 */
namespace Adminc\Model;
use Think\Model\RelationModel;
class AdmincModel extends RelationModel{

	// 数据关联
    protected $_link = array(
    	'Group'  =>  array(
		    'mapping_type'      	=>  self::MANY_TO_MANY,
		    'class_name'        	=>  'AuthGroup',
		    'mapping_name'      	=>  'groups',
		    'foreign_key'       	=>  'uid',
		    'relation_foreign_key'  =>  'group_id',
		    'relation_table'    	=>  'php_auth_group_access',
    	),
    );
    // 数据验证
	protected $_validate = array(
		// array(验证字段1,验证规则,错误提示,[验证条件,附加规则,验证时间]),
		array('user_name','require','请填写管理员账户', 1,'regex',3),
		array('group_id', 0,'请选择管理员职位', 1,'notequal',3),
	);

	protected $_auto = array(
		array('user_pass', 'md5', 3, 'function'),
		array('create_time', 'time', 1, 'function'),
	);

	public function admin_add(){
		$group_id = I('group_id', 0, 'intval');
		if ($this->create()) {
			if ($uid = $this->add()) {
				return M('AuthGroupAccess')->add(array('uid'=> $uid,'group_id'=> $group_id));
			}else{
				$this->error = '操作失败';
				return false;
			}
		}else{
			$this->error;
			return false;
		}
	}
	public function admin_edit(){
		if (empty($_POST['user_pass'])) {
			unset($_POST['user_pass']);
		}
		// 数据验证
		if ($this->create()) {
			$uid = I('uid', '', 'intval');
			$group_id = I('group_id', 0, 'intval');
			$status = $this->where(array('uid'=> $uid))->save();
			$group_access = M('AuthGroupAccess')->where(array('uid'=> $uid))->save(array('group_id'=> $group_id));

			if ($status !== false AND $group_access !== false) {
				return true;
			}else{
				$this->error = '操作失败';
				return false;
			}
		}else{
			$this->error;
			return false;
		}
	}

	/**
	 * [admin_del description]
	 * @return [type] [description]
	 */
	public function admin_del(){
		$uid = I('uid', 0, 'intval');
		if ($uid = 1) {
			$this->error = '无法删除系统管理员';
			return false;
		}
		// 开始删除
		$admin = $this->where(array('uid'=> $uid))->delete();
		$group_ac = M('AuthGroupAccess')->where(array('uid'=> $uid))->delete();
		// 判断返回
		if ($admin !== false AND $group_ac !== false) {
			return true;
		}else{
			$this->error = '操作失败';
			return false;
		}
	}
}